package com.labichaoka.chaoka.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.labichaoka.chaoka.R;

import java.io.IOException;

/**
 * TODO: document your custom view class.
 */
public class TopTitleBar extends RelativeLayout {

    private static final String back_action = "input keyevent " + KeyEvent.KEYCODE_BACK;
    private TextView tv_title;
    private ViewGroup rightContainer;

    private OnClickListener mDefaultOnclickListener =
            (v) -> {
                v.setEnabled(false);
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context
                        .INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                try {
                    Runtime.getRuntime().exec(back_action);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                v.setEnabled(true);
//                v.postDelayed(() -> v.setEnabled(true), 500L);
            };

    public TopTitleBar(Context context) {
        super(context);
        init(null, 0);
    }

    public TopTitleBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public TopTitleBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,53));
        LayoutInflater.from(getContext()).inflate(R.layout.ui_top_title, this, true);
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.TopTitleBar, defStyle, 0);
        String mTitle = a.getString(
                R.styleable.TopTitleBar_titleText);
        a.recycle();
        tv_title = (TextView) findViewById(R.id.tv_title);
        View rl_goback = findViewById(R.id.back_layout);
        tv_title.setText(mTitle != null ? mTitle : "");
        rl_goback.setOnClickListener(mDefaultOnclickListener);
        rightContainer = (ViewGroup) findViewById(R.id.right_container);
        setBackgroundResource(R.drawable.shape_gray_bottom_line_bg);
    }

    public void setTitle(String title) {
        tv_title.setText(title);
    }

    public String getTitle() {
        return tv_title.getText().toString();
    }


}
